var ws= null; //建立的连接
var lockReconnect= false;//是否真正建立连接
var timeout= 5*1000;//30秒一次心跳
var timeoutObj= null;//心跳心跳倒计时
var serverTimeoutObj= null;//心跳倒计时
var timeoutnum= null;//断开 重连倒计时
var global_callback = null; //监听服务端消息
var curi = null; //监听服务端消息
var cjwt = null; //监听服务端消息
// uri: 长链接地址<br>// jwt: 前后端连接凭证， 按需添加<br>// callback: 服务端消息回调函数
export function createWebscoket(uri, jwt, callback) {
  global_callback = callback
  curi = uri
  cjwt = jwt
  ws = new WebSocket(uri)

  ws.onopen = ()=>{
    ws.send(jwt)
    lockReconnect = true
    //开启连接心跳
    start()
  }
  ws.onmessage = onMessage
  ws.onerror = onError
  ws.onclose = onClose
}

//发送消息
export function onSend(message){
  console.log(`发送消息： ${message}`)
  ws.send(message)
}

//接受服务端消息
export function onMessage(res){
  console.log('消息：'+res.data)
  let msgData = res.data
  if (typeof msgData != 'object' && msgData != 'Connect success' && msgData != 'pong') {
    var data = msgData.replace(/\ufeff/g, "");
    var message = JSON.parse(data)
    //服务端消息回掉
    global_callback(message)

  }
  //重置心跳
  reset()
}

//连接失败
export function onError(){
  console.log('连接失败')
  ws.close()
  ws = null
  lockReconnect = false
}

//连接关闭
export function onClose(){
  console.log('连接关闭')
  lockReconnect = false
  reconnect()
}
//断开关闭
export function closeWs(){
  if(lockReconnect) {
    ws.close()
    ws = null
    lockReconnect = false
  }
}

// 发送心跳
export function start () {
  timeoutObj && clearTimeout(timeoutObj);
  serverTimeoutObj && clearTimeout(serverTimeoutObj);
  timeoutObj = setTimeout(function(){
    //这里发送一个心跳，后端收到后，返回一个心跳消息
    if (ws.readyState == 1) { //如果连接正常
      ws.send('ping');
    } else{  //否则重连
      reconnect()
    }
    // serverTimeoutObj = setTimeout(function() {
    //   //超时关闭
    //   ws.close();
    // }, timeout );
  }, timeout)
}
//重置心跳
export function reset(){
  var that = this;
  //清除时间
  clearTimeout(timeoutObj);
  //清除时间
  clearTimeout(serverTimeoutObj);
  start(); //重启心跳
}

//重新连接
export function reconnect() {
  if(lockReconnect) {
    return;
  };
  console.log(`重新连接`)
  lockReconnect = true;
  //没连接上会一直重连，设置延迟避免请求过多
  timeoutnum && clearTimeout(timeoutnum);
  timeoutnum = setTimeout(function () {
    createWebscoket(curi,cjwt,global_callback);//新连接
    lockReconnect = false;
  },5000);
}
